package com.loan.service;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Page;
import com.loan.enums.S;
import com.loan.model.Repay;
import com.loan.util.Money;
import com.loan.util.Str;

public class RepayService extends BaseService<Repay>{

	/**
	 * 分页信息
	 */ 
	public Page<Repay> list(int page, int size, Map<String, String> map, String orderBy) {
		return Repay.dao.paginate(page, size, buildSql("repay",Arrays.asList("is_delay", "is_divide", "is_sect", "plus", "repay_time", "real_repay_time", "status", "create_time", "cid", "real_name", "mobile", "user_id", "loan_id"),map,"  order by "+orderBy));
	}
	
	/**
	 * 获取等待还款的记录
	 */ 
	public List<Repay> findRepayByLoan(int loanId, String status) {
		return Repay.dao.find("select * from repay where loan_id=? and status=?", loanId, status);
	}
	
	/**
	 * 获取等待还款的记录
	 */ 
	public List<Repay> findRepayByLoan(int loanId) {
		return Repay.dao.find("select * from repay where loan_id=? order by id asc", loanId);
	}
	
	/**
	 * 计算用户代还款金额
	 */
	public List<Repay> findByUser(int userId) {
		return Repay.dao.find("select * from repay where user_id=? order by apply_period asc ",userId);
	}
	
	/**
	 * 计算用户代还款金额
	 */
	public List<Repay> findByUser(int userId,String month) {
		String where = "status='process'";
		if(Str.nb(month)) {
			where += " and repay_time>='"+month+"-01 00:00:00' and repay_time<='"+month+"-31 23:59:59'";
		}
		return Repay.dao.find("select * from repay where "+where+" and user_id=? ",userId);
	}
	
	/**
	 * 计算交易收益总额
	 */
	public double sumByLoan(int id) {
		Repay rp = Repay.dao.findFirst("select sum(period_total) as total from repay where status='还款中' and loan_id=?",id);
		return Money.get(rp.getDouble("total"));
	}

	public Repay unSuccess(int loanId) {
		return Repay.dao.findFirst("select * from repay where loan_id=? and status<>?", loanId, S.REPAY_SUCCESS);
	}
}
